package com.explorati.LeetCode94.inorderTraversal;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @ Author : Weijian_Wang
 * @ Date : Created in 22:22 2020/9/19 0019
 * @ Description ：前序 中序 后序 通用 的算法，只不过时间耗费长
 */
public class Solution2 {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public class ColorTreeNode{
        TreeNode treeNode;
        String color;

        public ColorTreeNode(TreeNode treeNode, String color) {
            this.treeNode = treeNode;
            this.color = color;
        }
    }

    /**
     * 给定一个二叉树，返回它的中序 遍历
     * @param root
     * @return
     */
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();

        if(root == null) {
            return res;
        }

        Stack<ColorTreeNode> stack = new Stack<ColorTreeNode>();
        //white代表第一次访问，gray代表第二次访问
        //第一次访问时将其压入栈，第二次打印此节点的值
        stack.push(new ColorTreeNode(root, "white"));
        while(!stack.isEmpty()) {
            ColorTreeNode colorTreeNode = stack.pop();

            if(colorTreeNode.color.equals("white")){
                if(colorTreeNode.treeNode.right != null) {
                    stack.push(new ColorTreeNode(root.right, "white"));
                }
                stack.push(colorTreeNode);
                if(colorTreeNode.treeNode.left != null) {
                    stack.push(new ColorTreeNode(root.left, "white"));
                }
            }else {
                res.add(colorTreeNode.treeNode.val);
            }
        }
        return res;
    }
}
